'''
Created on Feb 9, 2010

@author: oabalbin
'''
import numpy as np
from signatures.common.classes import bfrm_factor
from collections import deque, defaultdict

class geneparser():

    def list_of_names(self, inputfile):
        
        genlist=deque()
        for line in inputfile:        
            line = line.strip('\n')
            fields = line.split('\t')
            #print fields 
            # To skip headers, star reading samples in column 7 of the file
            if fields[0][0] == '#': 
                continue                             
            if fields[0]=='':
                continue
            else:
                genlist.append(fields[0])
        
        return genlist
    
    def list_of_names_in_line(self, inputfile):     

        genlist=deque()
        for line in inputfile:        
            line = line.strip('\n')
            genlist = line.split('\t')
            
        '''
        if '-' in  genlist:
            i = genlist.index('-')
            genlist.pop([i])
        '''
        
        return genlist
    
    def list_of_names_in_line_dictionary(self, inputfile):     

        genlist=defaultdict()
        for line in inputfile:        
            line = line.strip('\n')
            genlist0 = line.split('\t')
            #print genlist0[0], genlist0[1:]
            genlist[genlist0[0]]=genlist0[1:]
        
        return genlist

    
    def list_of_genes_kgXref(self, inputfile):
        """
        It parses the kgXref UCSC table in order to get a list of all possible genes.
        The list is used latter on for defining the universe of genes 
        """
        genlist=[]
        for line in inputfile:        
            line = line.strip('\n')
            fields = line.split('\t')
            # To skip headers, star reading samples in column 7 of the file
            if fields[0][0] == '#':
                continue                             
            if fields[0]=='' or fields[4]=='':
                continue
            else:
                genlist.append(fields[4])
           
        return list(set(genlist))
    
    
    def list_of_names_in_factor(self, inputfile):
        """
        Reads the list of genes in each factor generated by bfrm
        Returns a dictionary
        """
        genedic,sdgene={},{}
        factorlist=[]
        genelist=[]
        facnum=1
        
        for line in inputfile:
            line = line.strip('\n')
            fields = line.split('\t')
            
            if fields[1] == 'Factor number':
                if int(fields[2])!=1:
                    factorlist.append( bfrm_factor(facnum,genedic,sdgene) )
                    facnum = int(fields[2]) 
                    genedic,sdgene={},{}
                else:
                    continue                             
            else:
                genedic[fields[1]] = float(fields[2])
                genelist.append(fields[1])
                if fields[3] == '#### seed gene ####':
                    sdgene[fields[1]] = 1
                else:
                    sdgene[fields[1]] = 0
            
        return factorlist, list(set(genelist))
    
    def list_of_nameload_in_factor(self, inputfile,thisfactors):
        """
        Reads the list of genes in each factor generated by bfrm
        Returns a dictionary
        """
        genedic,sdgene={},{}
        factorlist=[]
        genelist=[]
        facnum=1
        reading=False
        
        for line in inputfile:
            line = line.strip('\n')
            fields = line.split('\t')
            lnf = len(fields)
            
            thisfactors = np.array(thisfactors)
            
            if reading and fields[1] != 'Factor number':
                genedic[fields[1]] = float(fields[2])
                genelist.append(fields[1])
                #print genedic
                if lnf == 4 and fields[3] == '#### seed gene ####':
                    sdgene[fields[1]] = 1
                else:
                    sdgene[fields[1]] = 0
                    
            if fields[1] == 'Factor number':
                if int(fields[2]) == 0:
                    continue
                
                if reading:
                    factorlist.append( bfrm_factor(facnum,genedic,sdgene) )
                    #print facnum
                    #print genedic
                    reading=False
                
                ishere = thisfactors[thisfactors==int(fields[2])]
                if ishere.size != 0:
                    #factorlist.append( bfrm_factor(facnum,genedic,sdgene) )
                    facnum = int(fields[2])
                    genedic,sdgene={},{}
                    reading=True
                else:
                    continue

        #print factorlist
        return factorlist, list(set(genelist))

    
                
'''
gp=geneparser()
names = gp.list_of_nameload_in_factor(open('/home/oabalbin/projects/networks/output/2010_03_15_00_43/bfrm/2010_03_15_00_43_geneInModules.txt'), range(5))
#print ",".join(names).replace(',','\t')
'''